﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace G.Data
{
    /// <summary>
    /// 伪数据库基类
    /// </summary>
    public abstract class FakeDataBase
    {
        private string DBAddress;

        public FakeDataBase(string dbAddress)
        {
            this.DBAddress = dbAddress;
        }
        private string securityKey;
        private bool isSecurity;
        /// <summary>
        /// 采用加密的方式保存数据
        /// </summary>
        /// <param name="dbAddress"></param>
        /// <param name="securityKey"></param>
        public FakeDataBase(string dbAddress, string securityKey)
            : this(dbAddress)
        {
            this.securityKey = securityKey;
            this.isSecurity = true;
        }

        private bool isInitialed;
        /// <summary>
        /// 初始化数据库中的数据
        /// </summary>
        /// <returns></returns>
        public virtual async Task InitialBatabaseAsync()
        {
            if (!isInitialed)
            {
                Type t = this.GetType();
                foreach (var item in t.GetTypeInfo().DeclaredFields)
                {
                    if (item.FieldType.Name == "Table`1")
                    {
                        string address = DBAddress + "_" + item.Name;
                        var value = await Utils.APPFileHelp.DeserializeObjectFromFile(address, item.FieldType, Utils.FileContentType.JSON, isSecurity, securityKey);
                        if (value == null)
                        {
                            item.SetValue(this, item.FieldType.CreateInstance(null));
                        }
                        else
                            item.SetValue(this, value);
                    }
                }
                isInitialed = true;
            }
        }
        /// <summary>
        /// 提交更改
        /// </summary>
        /// <returns></returns>
        public virtual async Task SubmitChanges()
        {
            Type t = this.GetType();
            foreach (var item in t.GetTypeInfo().DeclaredFields)
            {
                var itemType = item.FieldType;
                if (itemType.Name == "Table`1")
                {
                    var info = itemType.GetTypeInfo().GetDeclaredField("IsChanged");
                    var table = item.GetValue(this);
                    var value = (bool)info.GetValue(table);
                    if (value)
                    {
                        string address = DBAddress + "_" + item.Name;
                        await Utils.APPFileHelp.SerializeObjectToFile(address, table, Utils.FileContentType.JSON, isSecurity, securityKey);
                        info.SetValue(table, false);
                    }
                }
            }
        }

    }
}
